import { getDictionaryList } from '@/api/dictionary'

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useDictionaryStore = defineStore('dictionary', () => {
  const dictionaryMap = ref({})

  const setDictionaryMap = (groupCode,dictionaryList) => {
    dictionaryMap.value[groupCode] = { ...dictionaryMap.value[groupCode], ...dictionaryList }
  }

  const getDictionary = async(groupCode) => {
    if (dictionaryMap.value[groupCode] && dictionaryMap.value[groupCode].length) {
      return dictionaryMap.value[groupCode]
    } else {
      const res = await getDictionaryList({ pageNumber: 1, pageSize: 9999, state: 1, groupCode: groupCode })
      if (res.code === 0) {
        const dictionaryList = []
        res.data.list && res.data.list.forEach(item => {
			let v = item.value
			if("int" === item.dataType){
				v = Number(item.value)
			}
          dictionaryList.push({
            label: item.name,
            value: v,
			remark: item.remark
          })
        })
        setDictionaryMap(groupCode,dictionaryList)
        return dictionaryMap.value[groupCode]
      }
    }
  }

  return {
    dictionaryMap,
    setDictionaryMap,
    getDictionary
  }
})
